import 'dart:convert';

import 'package:meePet/app/Constants.dart';
import 'package:meePet/utils/LogUtils.dart';
import 'package:meePet/utils/ext/StringExt.dart';

import '../bean/UserBeanData.dart';
import '../utils/SPUtil.dart';

class UserManager {
  static UserManager? _instance;
  Data? _userInfo;

  static UserManager get() {
    _instance ??= UserManager();
    return _instance!;
  }

  ///登录或者修改用户信息时调用
  void savaUser(Data user) {
    LogUtils.i("更新保存当前用户数据${json.encode(user.toJson())}");
    SPUtil.save(Constants.keyUser, json.encode(user.toJson()));
    SPUtil.save(Constants.keyAuthToken,user.authToken.orEmpty());
    _userInfo=user;

  }

  ///退出登录是调用
  void clearUser() {
    SPUtil.save(Constants.keyUser, "");
    SPUtil.save(Constants.keyAuthToken,"");
    _userInfo=null;
  }

  Data? getUser() {
    if(_userInfo==null){
      String jsonStr=SPUtil.load(Constants.keyUser, defaultValue: "{}");
      _userInfo=Data.fromJson(json.decode(jsonStr));
    }
    return _userInfo;
  }

  bool isLogin() {
    return !getAuthToken().isNulOrEmpty();
  }

  bool isMember() {
    return ("1"==getUser()?.level);
  }

  String getMemberId() {
    String memberId="";
    if(getUser()!=null){
      memberId=getUser()!.memberId.orEmpty();
    }
    return memberId;
  }

  int getSex() {
    int sex=0;
    if(getUser()!=null){
      sex=getUser()!.gender??1;
    }
    return sex;
  }

  String getNicName() {
    String name="";
    if(getUser()!=null){
      name=getUser()!.nickname.orEmpty();
    }
    return name;
  }

  String getAvatar() {
    String avatar="";
    if(getUser()!=null){
      avatar=getUser()!.avatarUrl.orEmpty();
    }
    return avatar;
  }

  int getLevel() {
    int level=0;
    if(getUser()!=null){
      level=getUser()!.gender??0;
    }
    return level;
  }

  String? getAuthToken() {
    return SPUtil.load(Constants.keyAuthToken);
  }
}
